package com.example.myfirstapplication

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.provider.ContactsContract
import android.widget.ArrayAdapter
import androidx.appcompat.app.AlertDialog
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.example.myfirstapplication.utils.LOG
import com.example.myfirstapplication.utils.myToast
import kotlinx.android.synthetic.main.activity_runtime_permission.*

class RuntimePermissionActivity : AppCompatActivity() {

    private val permissionList = arrayOf(
        Manifest.permission.CALL_PHONE,
        Manifest.permission.READ_CONTACTS
    )
    private val contactsList = ArrayList<String>()
    private lateinit var contactsAdapter: ArrayAdapter<String>

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContentView(R.layout.activity_runtime_permission)

        contactsAdapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, contactsList)
        contactsListView.adapter = contactsAdapter
        initCheckPermission()

        contactsListView.setOnItemClickListener { parent, view, position, id ->
            val callData = contactsList[position].split("\n")
            AlertDialog.Builder(this).apply {
                setTitle("你是否要拨打${callData[0]}的电话？")
                setMessage("${callData[0]}的电话是：${callData[1]}")
                setPositiveButton("确定") { dialog, which ->
                    call(callData[1])
                }
                setNegativeButton("取消") { dialog, which ->
                    dialog.dismiss()
                }
                setCancelable(false)
                show()
            }
        }

        btnCallPhone.setOnClickListener {
            call("0")
        }
    }

    private fun initCheckPermission() {
        if (
            ContextCompat.checkSelfPermission(
                this, Manifest.permission.CALL_PHONE
            ) != PackageManager.PERMISSION_GRANTED
            ||
            (ContextCompat.checkSelfPermission(
                this, Manifest.permission.READ_CONTACTS
            ) != PackageManager.PERMISSION_GRANTED)
        ) {
            ActivityCompat.requestPermissions(this, permissionList, 1)
        } else {
            readContacts()
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        when (requestCode) {
            1 -> {
/*                LOG.i(permissions[0].toString())
                LOG.i(grantResults[0].toString())*/
                var countPermission = 0
                var denieMsg = ""
                if (grantResults.isNotEmpty()) {
                    for ((index, item) in grantResults.withIndex()) {
                        if (item == PackageManager.PERMISSION_GRANTED) {
                            countPermission++
                            LOG.i("${permissions[index]}:is grant")
                        } else {
                            denieMsg += getPermissionTitle(permissions[index]) + "【未授权】\n"
                            LOG.i("${permissions[index]}:is denied")
                        }
                    }
                }
                if (countPermission == grantResults.size) {
                    readContacts()
                } else {
                    denieMsg += "请对以上权限进行授权先啊亲！"
                    myToast(this, denieMsg)
                }
/*                if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    call()
                } else {
                    myToast(this, "没有打电话的权限，请先授权！")
                }*/
            }
        }
    }

    private fun readContacts() {
        val cursor = contentResolver.query(
            ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
            null, null, null, null
        )
        while (cursor!!.moveToNext()) {
            val displayName = cursor.getString(
                cursor.getColumnIndex(
                    ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME
                )
            )
            val number = cursor.getString(
                cursor.getColumnIndex(
                    ContactsContract.CommonDataKinds.Phone.NUMBER
                )
            )
            contactsList.add("displayName\n$number")
        }
        contactsAdapter.notifyDataSetChanged()
        cursor?.close()
    }

    private fun call(number: String) {
        val phoneNumber = callNumberET.text.toString()
        val callNumber = if (phoneNumber.isNotEmpty()) {
            number
        } else {
            phoneNumber
        }
        try {
            val intent = Intent(Intent.ACTION_CALL)
            intent.data = Uri.parse("tel:${phoneNumber}")
            startActivity(intent)
        } catch (e: SecurityException) {
            e.printStackTrace()
        }
    }
}